from flask import render_template, redirect, current_app, g
from flask import request, flash, url_for, jsonify
from flask_login import login_user, login_required, logout_user, current_user
from flask_sqlalchemy import get_debug_queries

from . import web
from app.forms.auth import RegisterForm, LoginForm, ResetPasswordForm, EmailForm, \
    ChangePasswordForm, MyEmailForm
from app.models.user import User
from app.models.base import db
from app.common.email import send_email


@web.route('/register', methods=['POST'])
def register():
    res = {
    }
    # 单个表单禁用csrf：生成表单时加入参数form = request.form(csrf_enabled=False)
    form = RegisterForm(request.form)
    if form.validate():
        user = User()
        user.set_attrs(form.data)
        user.gender = 1 if form.sex.data.strip() == "man" else 0
        user.avatar_url = "/statics/img/default.jpg"
        db.session.add(user)
        db.session.commit()
        # token = user.generate_confirmation_token()
        # send_email(user.email, 'Confirm Your Account',
        #            'email/confirm', user=user, token=token)
        login_user(user, False)
        # flash('一封激活邮件已发送至您的邮箱，请快完成验证', 'confirm')
        # 由于发送的是ajax请求，所以redirect是无效的
        # return render_template('index.html')
        # return redirect(url_for('web.index'))
        res = {
            "success": True,
        }
        return jsonify(res)
    myerror = []
    res["success"] = False
    for (err, msg) in form.errors.items():
        myerror.append(msg[0])
    res["msg"] = myerror
    return jsonify(res)


@web.route('/login', methods=['POST'])
def login():
    res = {}
    form = LoginForm(request.form)
    if form.validate():
        user = User.query.filter_by(userid=form.userid.data).first()
        if user.check_password(form.pwd.data):
            print(form.flag.data)
            if form.flag.data:
                login_user(user, remember=True)
            else:
                login_user(user, remember=False)
            next = request.args.get('next')
            if not next or not next.startswith('/'):
                next = url_for('web.logsuc')
            # 由于发送的是ajax请求，所以redirect是无效的
            # return redirect(next)
            res["msg"] = "success"
            res["next"] = next
            return jsonify(res)

        else:
            # flash('密码错误', category='login_error')
            res["msg"] = "wrong_pwd"
            return jsonify(res)
    if len(form.errors["userid"]):
        res["msg"] = "wrong_id"
    return jsonify(res)


@web.route('/fixmsg', methods=['POST'])
def fixmsg():
    res = {}
    uid = current_user.get_id()
    user = User.query.get(int(uid))
    userpwd = request.form["userpwd"]
    nickname = request.form["nickname"]
    tel = request.form["tel"]
    if user.check_password(userpwd):
        uid = current_user.get_id()
        user.nickname = nickname
        user.tel = tel
        user.pwd = userpwd
        db.session.add(user)
        db.session.commit()
        res["success"] = True
        res["message"] = "修改成功"
        return jsonify(res)
    res["success"] = False
    res["message"] = "密码错误"
    return jsonify(res)


@web.route('/logsuc', methods=['GET'])
@login_required
def logsuc():
    res = {}
    if not current_user.is_anonymous:
        uid = current_user.get_id()
        user = User.query.get(int(uid))
        res["data"] = {
            "nickname": user.nickname,
            "id": user.id,
            "userid": user.userid,
            "tel": user.tel,
            "avatar_url": user.avatar_url
        }
        # return json.dumps(res, default=lambda o: o.__dict__)
    else:
        res["data"] = False
    return render_template('logsuc.html', res=res)


@web.route('/reset/password', methods=['GET', 'POST'])
def forget_password_request():
    res = {}
    form = MyEmailForm(request.form)
    if form.validate():
        account_email = form.useremail.data
        user = User.query.filter_by(userid=account_email).first_or_404()
        send_email(form.useremail.data, '重置你的密码',
                   'email/reset_password', user=user,
                   token=user.generate_token())
        flash('一封邮件已发送到邮箱' + account_email + '，请及时查收')
        res["msg"] = "success"
        return jsonify(res)
    res["msg"] = "fail"
    return jsonify(res)


@web.route('/reset/password/<token>', methods=['GET', 'POST'])
def forget_password(token):
    res = {}
    if not current_user.is_anonymous:
        return redirect(url_for('web.index'))
    form = ResetPasswordForm(request.form)
    if request.method == 'POST' and form.validate():
        result = User.reset_password(token, form.password1.data)
        if result:
            flash('你的密码已更新,请使用新密码登录')
            res["success"] = True
            return jsonify(res)
        else:
            res["success"] = False
            return jsonify(res)
    return render_template('forget.html', token=token)


@web.route('/change/password', methods=['GET', 'POST'])
@login_required
def change_password():
    form = ChangePasswordForm(request.form)
    if request.method == 'POST' and form.validate():
        current_user.password = form.new_password1.data
        db.session.commit()
        flash('密码已更新成功')
        return redirect(url_for('web.personal'))
    return render_template('auth/change_password.html', form=form)


@web.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('web.index'))


@web.route('/register/confirm/<token>')
def confirm(token):
    pass
    if current_user.confirmed:
        return redirect(url_for('main.index'))
    if current_user.confirm(token):
        db.session.commit()
        flash('You have confirmed your account. Thanks!')
    else:
        flash('The confirmation link is invalid or has expired.')
    return redirect(url_for('main.index'))

# @web.route('/register/ajax', methods=['POST'])
# def register_ajax():
#     form = RegisterForm()
#     res = {}
#     if form.validate():
#         user = User(form.nickname.data,
#                     form.email.data, form.password.data)
#         db.session.add(user)
#         db.session.commit()
#         # account_email = form.email.data
#         id = current_user.getid();
#         user = User.query.filter_by(id=id).first_or_404()
#         send_email(user.email, '激活账号',
#                        'email/reset_password', user=user,
#                        token=user.generate_token())

#         login_user(user, False)
#         g.status = True
#         flash('一封激活邮件已发送至您的邮箱，请快完成验证', 'confirm')
#         # 由于发送的是ajax请求，所以redirect是无效的
#         res["success"] = True
#         return jsonify[res]
#     res["success"] = False
#     return jsonify[res]
